<?php
	class SignIn extends CI_Controller {
	
	public function __construct()
	{
		parent::__construct();
	}
	
	public function index()
	{
		$this->load->model('User_model', 'user');
		$this->load->helper('security');
		
		$this->load->view('signin_view');
		
		$this->form_validation->set_rules('UserName', 'Username', 'callback_user_check');
		$this->form_validation->set_rules('Password', 'Password', 'required');


		if( $this->form_validation->run() == FALSE )
		{
			$this->load->view('signin_view');
		}
		else
		{
			$this->session->unset_userdata('userID');

			$localUserName = $this->input->post('UserName', TRUE);
			$localUnhashedPW = $this->input->post('Password', TRUE);
			$password = do_hash( $localUnhashedPW );
			
			$user = $this->user->get_user_username( $localUserName );

			if( $password === $user['Password'])
			{
				//update our side of the database with the sessionID
				$sessionID = $this->session->userdata('session_id');
				$this->user->set_sessionID_for_user($user['UserID'], $sessionID);
				
				//update CI's side of the database with the current user
				$userData = array( 'userID'=>$user['UserID'], 'my_session_id'=>$sessionID );
				$this->session->set_userdata($userData);
				
				//go to the main page
				redirect(base_url());
			}
			else
			{
				$this->load->view('signin_view');
			}
		}
	}
	
	public function user_check( $user )
	{
		if( $user == NULL )
		{
			$this->form_validation->set_message('user_check', 'Username is required');
			return FALSE;
		}
		$dbuser = $this->user->get_user_username( $user );
		if( $dbuser == NULL )
		{
			$this->form_validation->set_message('user_check', 'Username not found');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
}
?>